package com.schedule;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.config.MQBusiHandler;
import com.model.MQMessageVO;
import com.model.RequestMessage;
import com.mqService.MQBaseServcie;
import com.mqService.MQMessageService;
import com.mqService.MQServcie;
import com.util.SpringContextUtils;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class MultithreadScheduleTask 
{
	@Autowired
	private MQMessageService mqMessageService;
	@Autowired
	private MQBusiHandler handler;

	@Async
	@Scheduled(cron = "0/30 * * * * ?") // 间隔10秒
	public void first() throws InterruptedException {
		System.out.println(
				"第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
		System.out.println();
		try {
			Properties props = handler.getMqHandlerProp();
			for(Object key : props.keySet()) 
			{
				List<MQMessageVO> messageList = mqMessageService.getMessage((String)key);
				for(MQMessageVO message:messageList) 
				{
					String fullName = props.getProperty((String)key);
					Class<?> service = Class.forName(fullName);
					String name=service.getSimpleName();
	    	    	MQBaseServcie<?> bean = (MQBaseServcie<?>) SpringContextUtils.getBean(name);
	    	    	Method methods = bean.getClass().getDeclaredMethod("process", List.class);
	    	        methods.setAccessible(true);
	    	        List<Object> data=JSONArray.parseArray(message.getMessage(),Object.class);
	    	        methods.invoke(bean,data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Thread.sleep(1000 * 10);
	}

	@Async
	@Scheduled(fixedDelay = 100000)
	public void second() {
		System.out.println(
				"第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
		System.out.println();
	}
}
